<!DOCTYPE html>
<html>
<head>
  <title>Vue2 列表双向绑定 Demo</title>
  <script src="vue.js"></script>
  <!-- 生产环境（压缩版） -->
  <script src="axios.js"></script>

</head>
<body>
  <div id="app">
    <!-- 列表渲染 -->
    <div v-for="(item, index) in items" :key="item.name" class="item">
      {{item.name}}:{{item.content}}
      <button @click="removeItem(index)">删除</button>
    </div>

    <!-- 添加新项 -->
    <input type="text" placeholder="请输入name" v-model="name">
    <input type="text" placeholder="请输入content" v-model="content">
    <button @click="addItem">添加新项</button>
  </div>

  <script>
    new Vue({
      el: '#app',
      data: {
        items: [
          { name: 1, content: '项目1' },
          { name: 2, content: '项目2' }
        ],
        name: '',
        content:''
      },
      // 组件创建时加载数据
      created() {
        this.fetchItems();
      },
      methods: {
        // 从服务器获取项目列表
        fetchItems() {
          axios.get('/api/items')
            .then(response => {
              this.items = response.data;
            })
            .catch(error => {
              console.error('获取数据失败:', error);
            });
        },
        // 添加新项目
        addItem() {
          if (!this.name || !this.content) {
            alert('请输入name和content');
            return;
          }
          
          const newItem = {
            name: this.name,
            content: this.content
          };
          
          axios.post('/api/items', newItem)
            .then(response => {
              if (response.data.success) {
                // 添加到本地数组
                this.items.push(newItem);
                // 清空输入框
                this.name = '';
                this.content = '';
              }
            })
            .catch(error => {
              console.error('添加失败:', error);
            });
        },
        // 删除项目
        removeItem(index) {
          const item = this.items[index];
          
          axios.delete(`/api/items/${item.name}`)
            .then(response => {
              if (response.data.success) {
                // 从本地数组中删除
                this.items.splice(index, 1);
              }
            })
            .catch(error => {
              console.error('删除失败:', error);
            });
        }
      }
    });
  </script>

  <style>
    .item {
      margin: 10px;
      padding: 10px;
      border: 1px solid #ddd;
    }
  </style>
</body>
</html>
